import { CreateUINode, UINode } from 'babylon-lib/gui/base/ui-node';
import { Stage } from 'babylon-lib/base/stage';
import * as Data from '../data/data';
import { Quaternion, Vector3 } from '@babylonjs/core/Maths/math.vector';
import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder';
import { RawAssetsUrl } from '../raw-assets-info';
import { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh';
import { Color3 } from '@babylonjs/core/Maths/math.color';
import { Material } from '@babylonjs/core/Materials/material';
import { StandardMaterial } from '@babylonjs/core/Materials/standardMaterial';
import { RenderOrder } from 'babylon-lib/misc/render-order';
import { Landscape } from '../stages/default-stage-components/landscape';
import { SoldierManager } from '../stages/default-stage-components/soldier-manager';


class Battery {

    private static _background: AbstractMesh;
    private static _volumn: AbstractMesh;
    private static readonly volumnStart = 0.6;
    private static readonly fullColor = Color3.FromHexString('#2eff43');
    private static readonly emptyColor = Color3.FromHexString('#ff2e00');
    private static curColor = new Color3();

    public static node: UINode;

    public static initialize(stage: Stage): void {
        this.initializeNode(stage);
        this.bindData(stage);
        this.setVolumn(this.volumnStart);
    }

    private static bindData(stage: Stage): void {
        const scope = Battery;
        const mt = Landscape.maxTime;
        Data.gameTime.onChange((o, n) => {
            const rat = (mt - n) / mt;
            scope.setVolumn(scope.volumnStart * rat);
            Color3.LerpToRef(scope.emptyColor, scope.fullColor, rat, scope.curColor);
            (scope._background.material as StandardMaterial).emissiveColor.copyFrom(scope.curColor);
            (scope._volumn.material as StandardMaterial).emissiveColor.copyFrom(scope.curColor);
            if (n > mt) {
                if (SoldierManager.signedSoldiers.length > 0) {
                    Data.taskStatus.value = Data.taskState.failed;
                } else {
                    if (SoldierManager.surviveSoldiers.length > 0) {
                        Data.taskStatus.value = Data.taskState.failed;
                    } else {
                        Data.taskStatus.value = Data.taskState.success;
                    }
                }
                Data.gameOn.value = false;
            }
        });
    }

    private static setVolumn(vol: number): void {
        this._volumn.scaling.x = Math.max(vol,1e-6);
    }

    private static initializeNode(stage: Stage): void {
        const node = CreateUINode('battery-node', stage.mainScene, {
            anchor: new Vector3(1, 0, 0),
            lockToCamera: true,
            xrRatio: { x: 0.7, y: 0.9 },
            display: true,
        });

        const bg = MeshBuilder.CreatePlane('battery-background', { size: 0.1 }, stage.mainScene);
        const texture = stage.loader(stage.mainScene).getTextureTaskInfo(RawAssetsUrl.textureBattery)?.texture!;
        const mat = new StandardMaterial('battery-background-material', stage.mainScene);
        mat.disableLighting = true;
        mat.opacityTexture = texture;
        mat.alphaCutOff = 0.5;
        mat.transparencyMode = Material.MATERIAL_ALPHATEST;
        mat.emissiveColor = new Color3().copyFrom(this.fullColor);
        bg.material = mat;
        bg.parent = node.container;
        bg.position.set(-0.1, -0.05, 0);
        bg.scaling.set(0.8, 0.8, 0.8);
        bg.rotationQuaternion = Quaternion.FromEulerAngles(0, 3.14159, 0);
        bg.renderingGroupId = RenderOrder.id(Data.orders.uiBack);

        const vm = MeshBuilder.CreatePlane('battery-volumn', { width: 0.05, height: 0.02 }, stage.mainScene);
        vm.position.set(-0.025, 0, 0);
        vm.bakeCurrentTransformIntoVertices();
        const mt = new StandardMaterial('battery-volumn-material', stage.mainScene);
        mt.disableLighting = true;
        mt.emissiveColor = new Color3().copyFrom(this.fullColor);
        vm.material = mt;
        vm.parent = node.container;
        vm.position.set(-0.072, -0.049, 0);
        vm.scaling.set(1, 1, 1);
        vm.rotationQuaternion = Quaternion.FromEulerAngles(0, 3.14159, 3.14159);
        vm.renderingGroupId = RenderOrder.id(Data.orders.ui);

        this._background = bg;
        this._volumn = vm;
        this.node = node;
    }

}


export { Battery };